const app = getApp();

Page({
  data: {
    form: {
      username: "",
      password: "",
      phone: "",
      verify: ""
    },
    isCodeDisabled: false,
    codeText: "获取验证码",
    codeCountdown: 60
  },

  handleInput(e) {
    const { key } = e.currentTarget.dataset;
    const { value } = e.detail;
    this.setData({
      [`form.${key}`]: value 
    });
  },

  async getCode() {
    const { phone } = this.data.form;

    if (!phone) {
      wx.showToast({
        title: "请先输入手机号",
        icon: "none",
        duration: 1500
      });
      return;
    }
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({
        title: "请输入正确的手机号",
        icon: "none",
        duration: 1500
      });
      return;
    }

    try {
      this.setData({
        isCodeDisabled: true,
        codeText: `${this.data.codeCountdown}秒后重新获取`
      });

      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: "http://localhost:8080/user/verify",
          method: "POST",
          data: this.data.form, 
          header: {
            "Content-Type": "application/json"
          },
          success: (resp) => resolve(resp),
          fail: (err) => reject(err)
        });
      });

      const { data } = res;
      if (data.code === 200) {
        wx.showToast({
          title: data.msg || "验证码发送成功",
          icon: "success",
          duration: 1500
        });

        const countdownTimer = setInterval(() => {
          const { codeCountdown } = this.data;
          if (codeCountdown <= 1) {
            clearInterval(countdownTimer);
            this.setData({
              codeText: "获取验证码",
              isCodeDisabled: false,
              codeCountdown: 60
            });
          } else {
            this.setData({
              codeCountdown: codeCountdown - 1,
              codeText: `${codeCountdown - 1}秒后重新获取`
            });
          }
        }, 1000);
      } else {
        wx.showToast({
          title: data.msg || "验证码发送失败",
          icon: "none",
          duration: 1500
        });
        this.setData({
          isCodeDisabled: false,
          codeText: "获取验证码"
        });
      }
    } catch (err) {
      console.error("获取验证码失败：", err);
      wx.showToast({
        title: "网络错误，请重试",
        icon: "none",
        duration: 1500
      });
      this.setData({
        isCodeDisabled: false,
        codeText: "获取验证码"
      });
    }
  },

  async registered() {
    const { username, password, phone, verify } = this.data.form;

    if (!username) {
      wx.showToast({ title: "请输入用户名", icon: "none" });
      return;
    }
    if (username.length < 3 || username.length > 20) {
      wx.showToast({ title: "用户名需3-20位", icon: "none" });
      return;
    }
    if (!password) {
      wx.showToast({ title: "请输入密码", icon: "none" });
      return;
    }
    if (password.length < 6 || password.length > 32) {
      wx.showToast({ title: "密码需6-32位", icon: "none" });
      return;
    }
    if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({ title: "请输入正确的手机号", icon: "none" });
      return;
    }
    if (!verify) {
      wx.showToast({ title: "请输入验证码", icon: "none" });
      return;
    }
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: "http://localhost:8080/user/registered",
          method: "POST",
          data: this.data.form, 
          header: {
            "Content-Type": "application/json"
          },
          success: (resp) => resolve(resp),
          fail: (err) => reject(err)
        });
      });

      const { data } = res;
      if (data.code === 200) {
        wx.showToast({
          title: data.msg || "注册成功",
          icon: "success",
          duration: 1500
        });
        setTimeout(() => {
          wx.navigateTo({
            url: "/pages/login/login"
          });
        }, 1500);
      } else {
        wx.showToast({
          title: data.msg || "注册失败",
          icon: "none",
          duration: 1500
        });
      }
  },
  onLoad(options) {},
  onReady() {},
  onShow() {},
  onHide() {},
  onUnload() {}
});